//
//  XQBirthdayChooseView.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/7.
//

import UIKit

class XQBirthdayChooseView: UIView {

    var selectRow : Int = 0
    
    var selectDateHandle: ((String) -> Void)?
    
    var dataSource : [String] = [] {
        didSet {
            if selectRow == dataSource.count + 1 {
                selectRow = dataSource.count + 1
            }
            self.tableView.reloadData()
        }
    }
    
    var selectData : String = "" {
        didSet {
            var index = 2
            for (idx,_) in dataSource.enumerated() {
                if dataSource[idx] == selectData {
                    index = idx
                    break
                }
            }
            
            self.selectRow = index + 2
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                let indexPath = IndexPath(row: self.selectRow, section: 0)
                self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
            }

        }
    }
    
    private lazy var tableView: UITableView = {
        let table = UITableView()
        table.register(XQBaseCustomPopCell.self, forCellReuseIdentifier: "XQBaseCustomPopCell")
        table.delegate = self
        table.dataSource = self
        table.showsHorizontalScrollIndicator = false
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = UIColor.clear
        table.separatorStyle = .none
        return table
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
        makeConstraints()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        makeUI()
        makeConstraints()
    }
    
    private func makeUI() {
        self.addSubview(self.tableView)
    }
    
    private func makeConstraints() {
        self.tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private func tableViewDidSelectAtIndexPath(indexPath : IndexPath) {
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == dataSource.count + 3 || indexPath.row == dataSource.count + 2) {
            return
        }
        self.selectRow = indexPath.row
        self.tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
        handle()
    }
    
    private func handle() {
        self.tableView.reloadData()
        selectDateHandle?(dataSource[selectRow - 2])
    }

}

extension XQBirthdayChooseView {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        selectRow = -1
        self.tableView.reloadData()
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let rowH = 46.0
        let targetY = targetContentOffset.pointee.y
        
        var targetRow = Int(targetY / rowH + (velocity.y > 0 ? 0.5 : -0.5))
        targetRow = max(0, min(targetRow, dataSource.count - 1))

        selectRow = targetRow + 2
        targetContentOffset.pointee.y = CGFloat(targetRow) * rowH
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        handle()
    }
}

extension XQBirthdayChooseView : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count + 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XQBaseCustomPopCell", for: indexPath) as! XQBaseCustomPopCell
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == dataSource.count + 3 || indexPath.row == dataSource.count + 2) {
            cell.content = ""
        }else {
            cell.content = "\(dataSource[indexPath.row - 2])"
        }
        let middleOne = indexPath.row == selectRow - 1 ||  indexPath.row == selectRow + 1
        let middleTwo = indexPath.row == selectRow - 2 ||  indexPath.row == selectRow + 2
        cell.position(middle: selectRow == indexPath.row, middleOne: middleOne, middleTwo: middleTwo)
        cell.onTapHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.tableViewDidSelectAtIndexPath(indexPath: indexPath)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 46
    }
}
